import cache from "./cache.js";
import md5 from "./md5.js"
export default {
	iGetInnerText(testStr) {
		var resultStr = testStr.replace(/\ +/g, ""); //去掉空格
		resultStr = testStr.replace(/[ ]/g, ""); //去掉空格
		resultStr = testStr.replace(/[\r\n]/g, ""); //去掉回车换行
		return resultStr;
	},
	unitConverter(num) {
		if (!num || isNaN(num)) {
			return '0'
		}
		// 此处为防止字符串形式的数值进来，因为toFixed方法只能用于数值型数
		num = Number(num)
		if (Math.abs(num) > 100000000) {
			return (num / 100000000).toFixed(2)
		} else {
			return (num / 10000).toFixed(2)
		}
	},

	delArrayValue(val, arr) {
		var index = arr.indexOf(val);
		if (index > -1) { //大于0 代表存在，
			arr.splice(index, 1); //存在就删除
		}
		return arr;
	},
	putArrayValue(val, arr) {
		arr.push(val)
		return arr;
	},
	/**
	 * 将对象转换为URL参数 - 序列化方式
	 * @param {Object} obj - 需要转换的对象
	 * @return {String} - 转换后的URL参数
	 */
	toQueryString(obj) {
		return Object.keys(obj).map(key => {
			return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`;
		}).join('&');
	},
	//签名生成
	createSign(params, data, baseKey) {
		let obj = {
			...params,
			...data,
		}
		for (let key in obj) {
			if (obj[key] == undefined) {
				throw new Error(`${key} 不能为undefined`)
			}
		}
		let str = this.objectToQuery(obj)
		str = str.split(/[\t\r\f\n\s]*/g).join('')
		str += baseKey;
		return md5(str)
	},
	objectToQuery() {
		let obj = arguments[0];
		let prefix = arguments[1];
		if (typeof obj !== "object") return "";
		const attrs = Object.keys(obj);
		return attrs.reduce((query, attr, index) => {
			if (typeof obj[attr] === "object") {
				const subPrefix = prefix ? `${prefix}[${attr}]` : attr;
				query += this.objectToQuery(obj[attr], subPrefix);
			} else {
				if (prefix) {
					query += `${prefix}[${attr}]=${obj[attr]}`;
				} else {
					query += `${attr}=${obj[attr]}`;
				}
			}
			// 判断是否是第一层最后一个循环
			if (index !== attrs.length - 1) query += "&";
			return query;
		}, "");
	},
	/**
	 * 多维对象转数组
	 * @param {Object} obj 
	 * @param {Array} listre
	 */
	toOneArray(obj, listre = []) {
		for (let key in obj) {
			if (typeof obj[key] == 'object') {
				this.toOneArray(obj[key], listre)
			} else {
				listre.push(obj[key])
			}
		}
	},

	params(key) {
		let url = location.search; //获取url中"?"符后的字串
		let theRequest = {};
		if (url.indexOf("?") !== -1) {
			let str = url.substr(1);
			let strs = str.split("&");
			for (let i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
			}
		}
		return key ? theRequest[key] : theRequest;
	},
	/**
	 * 格式化日期
	 * @param {string | number | Date} value 指定日期
	 * @param {string} format 格式化的规则
	 * @example
	 * ```js
	 * formatDate();
	 * formatDate(1603264465956);
	 * formatDate(1603264465956, "h:m:s");
	 * formatDate(1603264465956, "Y年M月D日");
	 * ```
	 */
	formatDate(value = Date.now(), format = "Y/M/D h:m:s") {
		const formatNumber = n => `0${n}`.slice(-2);
		const date = new Date(value);
		const formatList = ["Y", "M", "D", "h", "m", "s"];
		const resultList = [];
		resultList.push(date.getFullYear().toString());
		resultList.push(formatNumber(date.getMonth() + 1));
		resultList.push(formatNumber(date.getDate()));
		resultList.push(formatNumber(date.getHours()));
		resultList.push(formatNumber(date.getMinutes()));
		resultList.push(formatNumber(date.getSeconds()));
		for (let i = 0; i < resultList.length; i++) {
			format = format.replace(formatList[i], resultList[i]);
		}
		return format;
	},

	formatTime(time) {
		const d = new Date(time).getTime()
		const now = Date.now()
		const diff = (now - d) / 1000
		if (diff < 30) {
			return '刚刚'
		} else if (diff < 3600) {
			return Math.ceil(diff / 60) + '分钟前'
		} else if (diff < 3600 * 24) {
			return Math.ceil(diff / 3600) + '小时前'
		} else if (diff < 3600 * 24 * 2) {
			return '1天前'
		}else{
			return time
		}

	},
	getWelcomeText() {
		let h = new Date().getHours()
		if (h >= 6 && h < 9) {
			return "早上好";
		}
		if (h >= 9 && h < 12) {
			return "上午好";
		}
		if (h >= 12 && h < 14) {
			return "中午好";
		}
		if (h >= 14 && h < 18) {
			return "下午好";
		}
		if (h >= 18 && h < 23) {
			return "晚上好";
		}
		return "凌晨啦";
	},
	checkLogin(callback, isLogin = true, nologin) {
		let user = cache.get('UserInfo')

		if (!user && isLogin) {
			uni.$rui.route("/pages/user/login/login")
			return false;
		}
		if (typeof callback == "function" && user) {
			callback(user || {})
			return false;
		}
		if (typeof nologin === 'function') {
			nologin()
			return false;
		}
	},

	sortObjectByKey(array, key) {
		return array.sort(function(a, b) {
			var x = a[key];
			var y = b[key];
			return ((x < y) ? ((x > y) ? 1 : 0) : -1);

		});
	},

	/**
	 * 防抖函数
	 * @param {Function} func 
	 * @param {Number} duration
	 * @@return {Function}
	 */
	debounce(func, duration = 500) {
		let timerId;
		return function(...args) {
			clearTimeout(timerId)
			timerId = setTimeout(() => {
				func.apply(this, args)
			}, duration)
		}
	},

	getNowDay() {
		let n = new Date()
		let y = n.getFullYear()
		let m = n.getMonth() + 1
			m = m < 10 ? '0' + m : m;
		let d = n.getDate()
		return y + '' + m + '' + d
	}

}